package com.tarena.lbs.user.service.Impl;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.enums.PassportResultEnum;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.dao.repository.UserRepository;
import com.tarena.lbs.user.pojo.param.UserParam;
import com.tarena.lbs.user.pojo.po.UserPO;
import com.tarena.lbs.user.pojo.vo.UserVO;
import com.tarena.lbs.user.service.UserService;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public void register(UserParam param) throws BusinessException {
        // 参数校验
        if (!StringUtils.hasText(param.getPhone())) {
            throw new BusinessException(PassportResultEnum.BIND_ERROR);
        }
        if (!StringUtils.hasText(param.getPassword())) {
            throw new BusinessException(PassportResultEnum.EMPTY_PASSWORD);
        }

        // 检查手机号是否已注册
        UserPO existUser = userRepository.findByPhone(param.getPhone());
        if (existUser != null) {
            throw new BusinessException(PassportResultEnum.USER_EXIST);
        }

        // 创建用户对象
        UserPO user = new UserPO();
        BeanUtils.copyProperties(param, user);

        // 设置默认值
        user.setStatus(0); // 0-正常状态
        user.setRegTime(new Date()); // 设置注册时间
        user.setLastLogTime(new Date()); // 设置最后登录时间

        // 保存用户
        userRepository.save(user);
    }

    @Override
    public UserVO getUserDetail() throws BusinessException {
        // 从认证上下文中获取当前登录用户信息
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        if (userPrinciple == null) {
            throw new BusinessException(PassportResultEnum.USER_NONE_EXIST);
        }

        // 根据用户ID查询用户信息
        UserPO user = userRepository.findById(userPrinciple.getId());
        if (user == null) {
            throw new BusinessException(PassportResultEnum.USER_NONE_EXIST);
        }

        // 转换为VO对象
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        return userVO;
    }
}
